package com.zgx.plus.system.controller.system;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.zgx.plus.common.aop.Log;
import com.zgx.plus.common.base.BaseController;
import com.zgx.plus.common.enums.BusinessType;
import com.zgx.plus.common.exception.BizException;
import com.zgx.plus.common.response.R;
import com.zgx.plus.system.api.dto.SysDeptDto;
import com.zgx.plus.system.api.vos.SysDeptVo;
import com.zgx.plus.system.service.SysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.MessageFormat;
import java.util.List;
import java.util.Objects;

/**
 * 部门信息
 */
@RestController
@RequestMapping("/system/dept")
public class SysDeptController extends BaseController {
    @Autowired
    private SysDeptService deptService;

    /**
     * 获取部门列表
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list")
    public R list(SysDeptDto deptDTO) {
        return R.ok(deptService.selectDeptList(deptDTO));
    }

    /**
     * 查询部门列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/list/exclude/{deptId}")
    public R excludeChild(@PathVariable(value = "deptId", required = false) Long deptId) {
        List<SysDeptVo> depts = deptService.selectDeptList(SysDeptDto.builder().build());
        depts.removeIf(d -> Objects.equals(d.getDeptId(), deptId) || CollUtil.contains(StrUtil.split(d.getAncestors(), ","), deptId + ""));
        return R.ok(depts);
    }

    /**
     * 根据部门编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:dept:query')")
    @GetMapping(value = "/{deptId}")
    public R getInfo(@PathVariable Long deptId) {
        try {
            return R.ok(deptService.selectDeptById(deptId));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("获取部门ID为{0}失败：{1}", deptId, e.getMessage()));
        }
    }

    /**
     * 新增部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:add')")
    @Log(title = "部门管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysDeptVo dept) {
        try {
            dept.setCreateBy(getUsername());
            return R.ok(deptService.insertDept(dept));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("新增部门{0}失败：{1}", dept.getDeptName(), e.getMessage()));
        }
    }

    /**
     * 修改部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:edit')")
    @Log(title = "部门管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysDeptVo dept) {
        try {
            dept.setUpdateBy(getUsername());
            return R.ok(deptService.updateDept(dept));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("更新部门{0}失败：{1}", dept.getDeptName(), e.getMessage()));
        }
    }

    /**
     * 删除部门
     */
    @PreAuthorize("@ss.hasPermi('system:dept:remove')")
    @Log(title = "部门管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deptId}")
    public R remove(@PathVariable Long deptId) {
        try {
            return R.ok(deptService.deleteDeptById(deptId));
        } catch (BizException e) {
            return R.fail(e.getMessage());
        } catch (Exception e) {
            return R.fail(MessageFormat.format("删除部门{0}失败：{1}", deptId, e.getMessage()));
        }
    }
}







